package com.backpackerxl.blog.web;

import com.backpackerxl.blog.model.Type;
import com.backpackerxl.blog.service.BlogsService;
import com.backpackerxl.blog.service.TypeService;
import com.backpackerxl.blog.vomodel.BlogCount;
import com.backpackerxl.blog.vomodel.BlogQuery;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Author by：Backpackersxl
 * Date: 2021/5/12/012
 * Time: 19:24
 **/
@Controller
public class TypeShowController {

    private final TypeService typeService;

    private final BlogsService blogsService;

    public TypeShowController(TypeService typeService, BlogsService blogsService) {
        this.typeService = typeService;
        this.blogsService = blogsService;
    }

    @GetMapping("/types/{id}")
    public String types(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        @PathVariable Long id, Model model) {
        List<Type> types = typeService.listTypeTop(10000);
        if (id == -1 && !types.isEmpty()) {
            id = types.get(0).getId();
        }
        BlogQuery blogQuery = new BlogQuery();
        blogQuery.setTypeId(id);
        model.addAttribute("types", types);
        model.addAttribute("page", blogsService.listBlog(pageable, blogQuery));
        model.addAttribute("activeTypeId", id);
        return "type";
    }

    @RequestMapping("/type-count/loadtypeinfo")
    @ResponseBody
    public List<BlogCount> loadTypeInfo() {
        return typeService.listTypeCount();
    }
}
